﻿/*
 */

package com.railway.files.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import cn.org.rapid_framework.page.Page;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.railway.common.base.BaseStruts2Action;
import com.railway.common.base.IdGenerator;
import com.railway.common.constants.SysConstant;
import com.railway.common.util.ImageUtil;
import com.railway.common.util.Json;
import com.railway.common.util.StaticMap;
import com.railway.files.model.Files;
import com.railway.files.service.IFilesManager;
import com.railway.files.vo.query.FilesQuery;
import com.railway.news.model.Category;
import com.railway.news.model.CategoryUserLink;
import com.railway.news.model.News;
import com.railway.news.service.ICategoryManager;
import com.railway.news.service.INewsManager;

/**
 * 该模块主要用于维护前台所下载的软件。 软件列表：列出前台显示软件名称、地址、上传人、软件大小、软件格式等信息。每页显示20条内容，20条以上自动分页。
 * 软件上传：软件上传时须填写软件名称，软件描述两项信息，填写之后，点击“上传”按钮完成软件上传操作。软件大小应控制在512M以内。否则，提示软件过大，无法上传。
 * 软件删除：点击“删除”按钮，前台软件共享中除去相关软件信息，
 * 
 */

public class FilesAction extends BaseStruts2Action implements Preparable,
		ModelDriven {
	private ICategoryManager categoryManager;
	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;

	protected static final String LIST_JSP = "/admin/files/list.jsp";
	protected static final String LIST_JSP_PHOTO = "/admin/files/photo/list.jsp";
	protected static final String LIST_JSP_VIDEO = "/admin/files/video/list.jsp";
	protected static final String CREATE_JSP = "/admin/files/create.jsp";

	protected static final String CREATE_JSP_VIDEO = "/admin/files/video/create.jsp";
	protected static final String CREATE_JSP_PHOTO = "/admin/files/photo/create.jsp";

	protected static final String EDIT_JSP_VIDEO = "/admin/files/video/edit.jsp";
	protected static final String EDIT_JSP_PHOTO = "/admin/files/photo/edit.jsp";
	protected static final String EDIT_JSP = "/admin/files/edit.jsp";
	protected static final String SHOW_JSP = "/admin/files/show.jsp";
	protected static final String SHOW_JSP_PHOTO = "/admin/files/photo/show.jsp";
	protected static final String SHOW_JSP_VIDEO = "/admin/files/video/show.jsp";
	// redirect paths,startWith: !
	protected static final String LIST_ACTION = "!/files/Files/list.do?fileTypes=SOFT";
	protected static final String LIST_ACTION_PHOTO = "!/files/Files/list.do?fileTypes=PHOTO";
	protected static final String LIST_ACTION_VIDEO = "!/files/Files/list.do?fileTypes=VIDEO";
	private IFilesManager filesManager;

	private INewsManager newsManager;
	private Files files;
	java.lang.String id = null;
	private String[] items;
	// 初始的通过param指定的文件名属性
	private String param;
	private String fileName;

	// 指定要被下载的文件路径，struts.xml中配置
	// private String inputPath;
	public void setInputPath(String value) {
		// inputPath = value;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFileName() {
		return fileName;
	}

	public String deleteByAjax() {

		String fileTypes = this.getRequest().getParameter("fileTypes");
		String uploadedfileid = this.getRequest()
				.getParameter("uploadedfileid");
		if (uploadedfileid != null) {
			if (SysConstant.FILE_TYPE_ADDRESS.equals(fileTypes)) {

		

			} else if (SysConstant.FILE_TYPE_PAYMENT.equals(fileTypes)) {
				
			} else if (SysConstant.FILE_TYPE_DUTY.equals(fileTypes)) {
				
			} else {

				// 这里应该根据传入的文件id，查询出对应的文件名
				Files f1 = filesManager.getById(uploadedfileid);
				// 这里有点绕,解释一下，传进来的fileName上放置的是文件id,根据id查询出文件名，而服务端供下载的文件名存在paths属性里
				fileName = f1.getPaths();
				String url = "/" + SysConstant.getUploadPath(fileTypes) + "/"
						+ fileName;
				String savePath = ServletActionContext.getServletContext()
						.getRealPath(""); // 获取项目根路径
				File f = new File(savePath + url);
				if (f.exists()) {
					f.delete();
				}
				//删除数据库条目:
				filesManager.removeById(uploadedfileid);
				if (SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT
						.equals(fileTypes)) {//还得删除缩略图
                   url = url.substring(0,url.lastIndexOf(f1.getFileType()));
                   url = url+"_s"+f1.getFileType();
                   f = new File(savePath + url);
   				if (f.exists()) {
   					f.delete();
   				}
				}

			}

		}
		Map map = new HashMap();
		map.put("result", "success");
		return writeAjaxResponse(Json.toJson(map));

	}

	public InputStream getInputStream() throws Exception {
		Files f = null;
		String fileTypes = this.getRequest().getParameter("fileTypes");

		if (SysConstant.CATEGORY_TYPE_NEWS.equals(fileTypes)) {
			// 如果是新闻,则传递过来的fileName是新闻 id
			News n = newsManager.getById(fileName);
			fileName = (n.getContentHtml()).replaceAll(".xml", ".pdf");

		} else if (SysConstant.FILE_TYPE_ADDRESS.equals(fileTypes)) {

			fileName = "address.html";

		} else if (SysConstant.FILE_TYPE_DUTY.equals(fileTypes)) {
			fileName = "duty.html";
		}else if (SysConstant.FILE_TYPE_PAYMENT.equals(fileTypes)) {
			fileName = "payment.html";
		} else {

			// 这里应该根据传入的文件id，查询出对应的文件名
			f = filesManager.getById(fileName);
			// 这里有点绕,解释一下，传进来的fileName上放置的是文件id,根据id查询出文件名，而服务端供下载的文件名存在paths属性里
			fileName = f.getPaths();

		}
		String url = "/" + SysConstant.getUploadPath(fileTypes) + "/"
				+ fileName;
		if (f != null) {
			if ((SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT).equals(fileTypes)) {
				String memo = f.getMemo() == null ? "" : f.getMemo();
				fileName = new String(memo.getBytes(), "ISO8859-1")+f.getFileType();

			} else {
				String fn = f.getNames() == null ? "" : f.getNames();
				fileName = new String(fn.getBytes(), "ISO8859-1")+f.getFileType();
			}
		}

		int size = url.length() - 1;
		// 把url字符串中原有的反斜杠替换成斜杠，若不替换则会因为斜杠和反斜杠并存而导致错误
		for (int i = 0; i < size; i++) {
			url = url.replace("//", "/");
		}
		return ServletActionContext.getServletContext()
				.getResourceAsStream(url);
	}

	/**
	 * 根据软件分类id获得相应的软件列表
	 * 
	 * @return
	 */
	public String getFilesByCatId() {

		String catId = this.getRequest().getParameter("catId");
		// 查询最经更新的top count,简称tc
		String topcount = this.getRequest().getParameter("tc");

		FilesQuery query = newQuery(FilesQuery.class, DEFAULT_SORT_COLUMNS);
		query.setFileTypes(SysConstant.CATEGORY_TYPE_SOFTWARE_MANAGEMENT);
		query.setSortColumns("CREATE_TIME DESC");
		if (topcount != null && !"".equals(topcount)) {
			query.setTopcount(topcount);
		}
		if (catId != null && !"".equals(catId)) {
			query.setObjId(catId);
		}

		Map map = new HashMap();

		try {

			Page page = filesManager.findPage(query);
			map.put("total", page.getTotalCount());
			List list = page.getResult();
			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					Files f = (Files) list.get(i);
					f.setCatname(f.getCatname() == null ? "" : f.getCatname());
				}
			}
			map.put("rows", list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return writeAjaxResponse(Json.toJson(map));
	}

	public String download() throws Exception {
		/*
		 * 
		 * 获取目标文件在服务器中保存的目录。若不在这个目录则拒绝下载，否则，
		 * 
		 * 稍微精通struts2的人可能试图获取WEB-INF下的文件，那就不安全了。
		 * 
		 */

		String downloadDir = ServletActionContext.getServletContext()
				.getRealPath("/" + SysConstant.getMsgUploadPath());
		// 获取目标文件的绝对路径
		String downloadFile = ServletActionContext.getServletContext()
				.getRealPath("/" + SysConstant.getMsgUploadPath());
		/*
		 * 
		 * 防止企图下载不在目录downloadDir下的文件，以保障安全。若不在这个目
		 * 
		 * 录则拒绝下载，否则，稍微精通struts2的人可能试图获取WEB-INF下 的文件，那就不安全了。
		 * 
		 */

		if (!downloadFile.startsWith(downloadDir)) {
			return null;
		}
		return SUCCESS;
	}

	public void setParam(String param) {
		this.param = param;
	}

	public void prepare() throws Exception {
		if (isNullOrEmptyString(id)) {
			files = new Files();
		} else {
			files = (Files) filesManager.getById(id);
			//			
			// String ft = this.getRequest().getParameter("fileTypes");
			// if(SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT.equals(ft) ||
			// SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT.equals(ft)){
			// Category category = (Category) categoryManager.getById(id);
			// Map map = new HashMap();
			// map.put("catId", id);
			// try{
			//					
			// List list = categoryManager.getUsernamesByMap(map);
			//				
			// StringBuffer msb = new StringBuffer();
			// StringBuffer vsb = new StringBuffer();
			// StringBuffer csb = new StringBuffer();
			//				
			// StringBuffer msb1 = new StringBuffer();
			// StringBuffer vsb1 = new StringBuffer();
			// StringBuffer csb1 = new StringBuffer();
			// if(list != null){
			//					
			// for(int i = 0 ; i < list.size();i++){
			//						
			// CategoryUserLink c = (CategoryUserLink)list.get(i);
			// if("C".equals(c.getState())){
			// String unames = StaticMap.getUserValue(c.getUserid());
			// csb.append(unames);
			// csb.append(",");
			//							
			// String udis = c.getUserid();
			// csb1.append(udis);
			// csb1.append(",");
			// }else if("M".equals(c.getState())){
			// String unames = StaticMap.getUserValue(c.getUserid());
			// msb.append(unames);
			// msb.append(",");
			//							
			// String udis = c.getUserid();
			// msb1.append(udis);
			// msb1.append(",");
			// }else if("V".equals(c.getState())){
			// String unames = StaticMap.getUserValue(c.getUserid());
			// vsb.append(unames);
			// vsb.append(",");
			//							
			// String udis = c.getUserid();
			// vsb1.append(udis);
			// vsb1.append(",");
			// }
			//						
			//						
			// }
			//					
			// }
			// files.setCheckernames(csb.toString());
			// files.setVisitornames(vsb.toString());
			// files.setMaintainernames(msb.toString());
			//				
			// files.setCheckerid(csb1.toString());
			// files.setVisitorid(vsb1.toString());
			// files.setMaintainerid(msb1.toString());
			// }catch(Exception e){
			// e.printStackTrace();
			// }
			// }
		}
	}

	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写 */
	public void setFilesManager(IFilesManager manager) {
		this.filesManager = manager;
	}

	public Object getModel() {
		return files;
	}

	public void setId(java.lang.String val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	/** 执行搜索 */
	public String list() {

		String fileTypes = files.getFileTypes();
		if ((SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT).equals(fileTypes)) {
			return LIST_JSP_PHOTO;
		} else if ((SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT)
				.equals(fileTypes)) {
			return LIST_JSP_VIDEO;
		} else {
			return LIST_JSP;
		}
	}

	public String listAjax() {

		String temp_types = this.getRequest().getParameter("fileTypes");

		FilesQuery query = newQuery(FilesQuery.class, DEFAULT_SORT_COLUMNS);
		query.setSortColumns("CREATE_TIME  desc");
		query.setFileTypes(temp_types);
		Map map = new HashMap();
		try {
			Page page = filesManager.findPage(query);

			map.put("total", page.getTotalCount());
			map.put("rows", page.getResult());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return writeAjaxResponse(Json.toJson(map));
	}
	public String listAjaxManage() {

		String temp_types = this.getRequest().getParameter("fileTypes");
		String current_user_id = (String) this.getRequest().getSession()
		.getAttribute("userId");
		String username= (String) this.getRequest().getSession()
		.getAttribute("username");
		FilesQuery query = newQuery(FilesQuery.class, DEFAULT_SORT_COLUMNS);
		if(!username.equals("admin")){
			query.setCreator(username);
		}
		
		query.setSortColumns("CREATE_TIME desc");
		query.setFileTypes(temp_types);
		Map map = new HashMap();
		try {
			Page page = filesManager.findPage(query);

			map.put("total", page.getTotalCount());
			map.put("rows", page.getResult());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return writeAjaxResponse(Json.toJson(map));
	}
	/** 查看对象 */
	public String show() {
		String fileTypes = files.getFileTypes();
		if ((SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT).equals(fileTypes)) {
			return SHOW_JSP_PHOTO;
		} else if ((SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT)
				.equals(fileTypes)) {
			return SHOW_JSP_VIDEO;
		} else {

			return SHOW_JSP;
		}
	}

	public String showFileImg() {

		return "/admin/files/video/fileimg.jsp";
	}

	/** 进入新增页面 */
	public String create() {
		String fileTypes = this.getRequest().getParameter("fileTypes");
		if ((SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT).equals(fileTypes)) {
			return CREATE_JSP_PHOTO;
		} else if ((SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT)
				.equals(fileTypes)) {
			return CREATE_JSP_VIDEO;
		} else {
			return CREATE_JSP;
		}
	}

	/** 保存新增对象 */
	public String save() {
		try {
			String temp_fileTypes = files.getFileTypes();

			String uid = files.getUploadedfileid();
			String name = files.getNames();
			String memo = files.getMemo();
			String objId = files.getObjId();
			String fileImg = files.getFileImg();
			if (uid != null && !"".equals(uid)) {
				files = filesManager.getById(files.getUploadedfileid());
			}

			Date date = new Date(System.currentTimeMillis());
			files.setCreateTime(date);
			files.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			files.setCreateTimeString(sdf.format(date));
			String current_user_id = (String) this.getRequest().getSession()
					.getAttribute(SysConstant.USER_ID);
			files.setCreator(StaticMap.getUserValue(current_user_id));
			files.setFileTypes(temp_fileTypes);
			if (uid != null) {
				if (SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT
						.equals(temp_fileTypes)) {
					files.setFileImg(fileImg);// 题头图片
				}
				files.setNames(name);
				files.setMemo(memo);
				files.setObjId(objId);
				filesManager.update(files);
			} else {
				filesManager.save(files);
			}

			if ((SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT)
					.equals(temp_fileTypes)) {
				List list = new ArrayList();
				String maintainerids = this.getRequest().getParameter(
						"maintainerid");
				if (maintainerids != null) {

					String[] uids = maintainerids.split(",");
					for (int i = 0; i < uids.length; i++) {

						CategoryUserLink culink = new CategoryUserLink();
						culink.setId(IdGenerator.genUUIDStr());
						culink
								.setCategoryid(SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT);
						culink.setState("M");
						culink.setUserid(uids[i]);
						list.add(culink);
					}

				}
				// 照片,保存审核人

				String cids = this.getRequest().getParameter("checkerid");
				if (cids != null) {

					String[] uids = cids.split(",");
					for (int i = 0; i < uids.length; i++) {

						CategoryUserLink culink = new CategoryUserLink();
						culink.setId(IdGenerator.genUUIDStr());
						culink
								.setCategoryid(SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT);
						culink.setState("C");
						culink.setUserid(uids[i]);
						list.add(culink);
					}

				}
				categoryManager.saveCategoryUserLink(list);

				return LIST_ACTION_PHOTO;
			} else if ((SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT)
					.equals(temp_fileTypes)) {
				List list = new ArrayList();
				String maintainerids = this.getRequest().getParameter(
						"maintainerid");
				if (maintainerids != null) {

					String[] uids = maintainerids.split(",");
					for (int i = 0; i < uids.length; i++) {

						CategoryUserLink culink = new CategoryUserLink();
						culink.setId(IdGenerator.genUUIDStr());
						culink
								.setCategoryid(SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT);
						culink.setState("M");
						culink.setUserid(uids[i]);
						list.add(culink);
					}

				}
				String cids = this.getRequest().getParameter("checkerid");
				if (cids != null) {

					String[] uids = cids.split(",");
					for (int i = 0; i < uids.length; i++) {

						CategoryUserLink culink = new CategoryUserLink();
						culink.setId(IdGenerator.genUUIDStr());
						culink
								.setCategoryid(SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT);
						culink.setState("C");
						culink.setUserid(uids[i]);
						list.add(culink);
					}

				}
				categoryManager.saveCategoryUserLink(list);
				return LIST_JSP_VIDEO;
			} else {
				return LIST_ACTION;
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.print(e);
			return LIST_ACTION;
		}
	}

	/** 进入更新页面 */
	public String edit() {
		String fileTypes = files.getFileTypes();
		if ((SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT).equals(fileTypes)) {
			return EDIT_JSP_PHOTO;
		} else if ((SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT)
				.equals(fileTypes)) {
			return EDIT_JSP_VIDEO;
		} else {
			return EDIT_JSP;
		}
	}

	/** 保存更新对象 */
	public String update() {

		String fileTypes = files.getFileTypes();
		if ((SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT).equals(fileTypes)) {
			Files temp = filesManager.getById(this.files.getId());
			String uploadfileid = this.files.getUploadedfileid();
			if (uploadfileid != null && !"".equals(uploadfileid)) {
				// 赋值给要修改的
				temp = filesManager.getById(uploadfileid);
				this.files.setCtxpaths(temp.getCtxpaths());
				this.files.setPaths(temp.getPaths());
				this.files.setFileType(temp.getFileType());
				// 删除掉新传的,它已经没有意义了
				filesManager.removeById(uploadfileid);
			}
			filesManager.update(this.files);
			return LIST_ACTION_PHOTO;
		} else if ((SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT)
				.equals(fileTypes)) {
			Files temp = filesManager.getById(this.files.getId());
			String img = this.files.getFileImg();
			if (img == null || "".equals(img)) {
				this.files.setFileImg(temp.getFileImg());
			}
			// 获得新传的
			String uploadfileid = this.files.getUploadedfileid();
			if (uploadfileid != null && !"".equals(uploadfileid)) {
				// 赋值给要修改的
				temp = filesManager.getById(uploadfileid);
				this.files.setCtxpaths(temp.getCtxpaths());
				this.files.setPaths(temp.getPaths());
				this.files.setFileType(temp.getFileType());
				// 删除掉新传的,它已经没有意义了
				filesManager.removeById(uploadfileid);
			}
			filesManager.update(this.files);
			return LIST_JSP_VIDEO;
		} else {
			filesManager.update(this.files);
			return LIST_ACTION;
		}
	}

	/** 删除对象 */
	public String delete() {
		String fileTypes = this.getRequest().getParameter("fileTypes");
		if (items != null)
			for (String ids : items) {
				String[] idArray = ids.split(",");
				for (String id : idArray) {
					filesManager.removeById(id);
				}
			}
		if ((SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT).equals(fileTypes)) {
			return LIST_ACTION_PHOTO;
		} else if ((SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT)
				.equals(fileTypes)) {
			return LIST_JSP_VIDEO;
		} else {
			return LIST_ACTION;
		}
	}

	private File fileupload; // 和JSP中input标记name同名

	// Struts2拦截器获得的文件名,命名规则，File的名字+FileName
	// 如此处为 'fileupload' + 'FileName' = 'fileuploadFileName'
	private String fileuploadFileName; // 上传来的文件的名字

	public File getFileupload() {
		return fileupload;
	}

	public void setFileupload(File fileupload) {
		this.fileupload = fileupload;
	}

	public String getFileuploadFileName() {
		return fileuploadFileName;
	}

	public void setFileuploadFileName(String fileuploadFileName) {
		this.fileuploadFileName = fileuploadFileName;
	}

	public String upload() throws Exception {
		String sizestr = "";
		String db = this.getRequest().getParameter("fileTypes");

		String extName = ""; // 保存文件拓展名
		String newFileName = ""; // 保存新的文件名
		String nowTimeStr = ""; // 保存当前时间
		SimpleDateFormat sDateFormat;
		Random r = new Random();
		String tempctxpaths = this.getRequest().getContextPath() + "/"
				+ SysConstant.getUploadPath(db) + "/";
		String savePath = ServletActionContext.getServletContext().getRealPath(
				""); // 获取项目根路径
		savePath = savePath + File.separator + SysConstant.getUploadPath(db)
				+ File.separator;

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8"); // 务必，防止返回文件名是乱码

		// 生成随机文件名：当前年月日时分秒+五位随机数（为了在实际项目中防止文件同名而进行的处理）
		int rannum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000; // 获取随机数
		sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); // 时间格式化的格式
		nowTimeStr = sDateFormat.format(new Date()); // 当前时间

		// 获取拓展名
		if (fileuploadFileName.lastIndexOf(".") >= 0) {
			extName = fileuploadFileName.substring(fileuploadFileName
					.lastIndexOf("."));
		}

		newFileName = nowTimeStr + rannum + extName; // 文件重命名后的名字

		Map map = new HashMap();
                

//	 if (SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT.equals(db)) {
////
//		} else {

			String generated_id = IdGenerator.genUUIDStr();

			if (SysConstant.FILE_TYPE_ADDRESS.equals(db)) {
				newFileName = "address.html"; // 文件重命名后的名字

				// 如果是通讯录,先删除旧的
				FilesQuery query = newQuery(FilesQuery.class,
						DEFAULT_SORT_COLUMNS);
				query.setFileTypes(SysConstant.FILE_TYPE_ADDRESS);
				Page page = filesManager.findPage(query);
				List list = page.getResult();
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {

						Files faddr = (Files) list.get(i);
						File fd = new File(savePath + faddr.getPaths());
						if (fd.exists()) {
							fd.delete();
						}

						filesManager.removeById(faddr.getId());
					}
				}

				map.put("addressid", generated_id);
				map.put("addressname", fileuploadFileName);

			} else if (SysConstant.FILE_TYPE_DUTY.equals(db)) {
				newFileName = "duty.html"; // 文件重命名后的名字
				// 如果是通讯录,先删除旧的
				FilesQuery query = newQuery(FilesQuery.class,
						DEFAULT_SORT_COLUMNS);
				query.setFileTypes(SysConstant.FILE_TYPE_DUTY);
				Page page = filesManager.findPage(query);
				List list = page.getResult();
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {

						Files faddr = (Files) list.get(i);
						File fd = new File(savePath + faddr.getPaths());
						if (fd.exists()) {
							fd.delete();
						}

						filesManager.removeById(faddr.getId());
					}
				}

				map.put("addressid", generated_id);
				map.put("addressname", fileuploadFileName);

			} else if (SysConstant.FILE_TYPE_PAYMENT.equals(db)) {
				newFileName = "payment.html"; // 文件重命名后的名字
				// 如果是通讯录,先删除旧的
				FilesQuery query = newQuery(FilesQuery.class,
						DEFAULT_SORT_COLUMNS);
				query.setFileTypes(SysConstant.FILE_TYPE_PAYMENT);
				Page page = filesManager.findPage(query);
				List list = page.getResult();
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {

						Files faddr = (Files) list.get(i);
						File fd = new File(savePath + faddr.getPaths());
						if (fd.exists()) {
							fd.delete();
						}

						filesManager.removeById(faddr.getId());
					}
				}

				map.put("addressid", generated_id);
				map.put("addressname", fileuploadFileName);

			}
			String npath = savePath + newFileName;
			File f = new File(npath);
			fileupload.renameTo(f); // 保存文件

			FileInputStream fis = null;
			// 在服务端计算文件大小，回显给客户端
			try {

				fis = new FileInputStream(f);
				long filesize = 0L;
				filesize = fis.available();
				java.text.DecimalFormat myformat = new java.text.DecimalFormat(
						"0.00");
				float tempsize = Float.parseFloat(String.valueOf(filesize)) / 1048576;
				sizestr = myformat.format(tempsize);
			} catch (Exception e1) {
				e1.printStackTrace();
			} finally {
				if (fis != null) {
					fis.close();
				}
			}
		//	String s_name = null;
			// 如果是上传摄影图片,则生成缩略图
			if (SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT.equals(db)) {

				ImageUtil iutil = new ImageUtil();
			//	s_name = nowTimeStr + rannum+ "_s" + extName;
				iutil.saveImageAsJpg(npath, savePath + nowTimeStr + rannum
						+ "_s" + extName, 100, 100);
			}

			// 对文件信息进行持久化
			Files tf = new Files();
			try {

				tf.setCreateTime(new Date(System.currentTimeMillis()));
				tf.setCreateTimeString(new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss").format(new Date(System
						.currentTimeMillis())));
				tf.setNames(fileuploadFileName);
				tf.setFileType(extName);
				String current_user_id = (String) this.getRequest()
						.getSession().getAttribute("userId");

				tf.setCreator(StaticMap.getUserValue(current_user_id));
				tf.setMemo("");
				tf.setFilesize(sizestr);//设置文件大小
				tf.setOrderNo(new Integer(1));
				// 这里必须放新文件名,否则文件下载不好使
				tf.setPaths(newFileName);//
			//	if(s_name != null){
				//	tf.setCtxpaths(tempctxpaths + s_name);// 这里修正一下
			//	}else{
				    tf.setCtxpaths(tempctxpaths + newFileName);// 这里修正一下
				//}
				tf.setObjId("");
				tf.setFileTypes(db);
				tf.setState(new Long(1));
				tf.setId(generated_id);
				filesManager.save(tf);
				map.put("uploadedfileid", tf.getId());

			} catch (Exception e) {
				e.printStackTrace();
			}

//		}

		map.put("uploadedresult", fileuploadFileName + "(大小:" + sizestr
				+ "M)上传成功!");
		map.put("uploadedpaths", savePath);
		if (SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT_HEAD.equals(db)|| SysConstant.CATEGORY_TYPE_NEWS.equals(db) || SysConstant.CATEGORY_TYPE_NEWS_HEAD.equals(db) || SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT.equals(db)
				|| SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT.equals(db)) {
			map.put("fileImgpath", tempctxpaths + newFileName);
		}
		return writeAjaxResponse(Json.toJson(map));
	}

	public void setNewsManager(INewsManager newsManager) {
		this.newsManager = newsManager;
	}

	public void setCategoryManager(ICategoryManager categoryManager) {
		this.categoryManager = categoryManager;
	}
}
